<!--
 * @Descripttion:账单管理-每日销售报表
 * @Author: 森哥
 * @Date: 2022-11-07 11:46:33
 * @LastEditors: xiaodi 53527718@qq.com
 * @LastEditTime: 2025-10-10 16:38:14
-->
<template>
  <div>
    <div class="dailySale-content-wrap">
      <!-- 左边盒子 -->
      <div class="left-box">
        <div class="dailySale-title">每日销售报表</div>
        <!-- 装搜索部分以及表格等的盒子 -->
        <div class="dailySale-list-wrap">
          <!-- 头部搜索栏 -->
          <div class="search-box-wrap">
            <el-row>
              <!-- 查询时间 -->
              <el-col :span="8" class="betweenTime-box">
                <el-date-picker
                  v-model="dateRangeList"
                  type="daterange"
                  range-separator="至"
                  start-placeholder="开始时间"
                  end-placeholder="结束时间"
                  value-format="YYYY-MM-DD"
                >
                </el-date-picker>
              </el-col>
              <!-- 选择餐段 -->
              <el-col :span="4" class="payMethod-box">
                <!-- <span class="payMethod-text">支付方式</span> -->
                <el-select v-model="searchParam.time_slot" class="select" placeholder="请选择餐段">
                  <el-option
                    v-for="item in dinnerList"
                    :key="item.value"
                    :label="item.label"
                    :value="item.value"
                  >
                  </el-option>
                </el-select>
              </el-col>
              <!-- 输入框 -->
              <el-col :span="3" class="search-input-box">
                <span class="search-btn" @click="queryForm">查询</span>
              </el-col>
              <el-col :span="3" class="search-input-box">
                <span class="search-btn" @click="showCategoryStatistics">
                  {{ isCategoryStatistics ? '分类统计' : '菜品统计' }}
                </span>
              </el-col>
            </el-row>
          </div>
        </div>
        <div class="table-wrap">
          <BusinessTableList
            @singleElection="singleElection"
            :table-data="tableData"
            :loading="tableLoading"
          />
        </div>
        <!-- 表格数据总数 -->
        <!-- <div class="table-total">
          <span>共{{ pageListTotal }}条</span>
          <div>
            <pagination
              :total="pageListTotal"
              :page.sync="pageListQuery.page"
              :limit.sync="pageListQuery.limit"
              @pagination="getDeskOrderList"
              :pageSizes="[15, 30, 45, 100]"
            />
          </div>
        </div> -->
        <!-- 表格数据汇总&&按钮组 -->
        <div class="data-summary-box">
          <div class="sumary-btn-group">
            <span class="cancel-closing" @click="printTicket">打印票据</span>
            <span class="cancel" @click="handleAction">返回</span>
          </div>
        </div>
      </div>

      <!-- 右边盒子 -->
      <div class="right-box">
        <dailySaleSummaryCard
          :summary="summary"
          :discountSummary="discountSummary"
          :payMethodsList="payMethodsList"
          :returnFoodList="returnFoodList"
          :shopInfo="shopInfo"
          :detailData="detailData"
          :loading="cardLoading"
          :isCategoryStatistics="isCategoryStatistics"
        />
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'

import { salesReport } from '@/api/dailySaleSummary'
import { getNowDateAndTime } from '@/utils/index'
import { debounce } from '@/utils/toolsValidate'

import BusinessTableList from './components/BusinessTableList.vue'
import dailySaleSummaryCard from './components/dailySaleSummaryCard.vue'

// 初始化路由
const router = useRouter()

// 定义响应式数据
const pageListTotal = ref(0)
const pageListQuery = ref({})
const dateRangeList = ref([])
const tableData = ref([])
// 加载状态
const tableLoading = ref(false)
const cardLoading = ref(false)

// 餐段列表
// 0全部 1早市 2午市 3晚市 4夜市
const dinnerList = ref([
  {
    label: '早市',
    value: 1
  },
  {
    label: '午市',
    value: 2
  },
  {
    label: '晚市',
    value: 3
  },
  {
    label: '夜市',
    value: 4
  }
])

// 查询参数
const searchParam = ref({
  time_slot: ''
})

// 子组件的收银汇总列表
const payMethodsList = ref([])
// 子组件的退菜明细表
const returnFoodList = ref([])
const summary = ref({})
const discountSummary = ref([])
const shopInfo = ref({})
const detailData = ref({})
const isCategoryStatistics = ref(true)

// 返回上一页
const handleAction = () => {
  router.go(-1)
}

// 打印票据
const printTicket = () => {
  let start_time = ''
  let end_time = ''
  if (dateRangeList.value) {
    start_time = dateRangeList.value[0] + ' 00:00:00'
    end_time = dateRangeList.value[1] + ' 23:59:59'
  }
  salesReport({
    start_time: start_time,
    end_time: end_time,
    time_slot: searchParam.value.time_slot,
    print: '1',
    is_category_statistics: isCategoryStatistics.value ? 1 : 0
  })
    .then(res => {
      ElMessage.success('推送打印成功')
    })
    .catch(error => {
      ElMessage.error('打印失败，请重试')
    })
}

// 按分类统计
const categoryStatistics = () => {
  let payTypeSummary = detailData.value.payTypeSummary?.list || []
  let summaryData = detailData.value.summary || {}
  let discountSummaryData = detailData.value.discountSummary?.list || []
  let backList = detailData.value.categoryList?.backList || []
  let foodList = detailData.value.categoryList?.foodList || []
  let presentList = detailData.value.categoryList?.presentList || []

  let numberList = [
    payTypeSummary.length,
    discountSummaryData.length,
    backList.length,
    foodList.length, 
    presentList.length
  ]

  payMethodsList.value = payTypeSummary || []
  returnFoodList.value = backList || [] 
  summary.value = summaryData || {}
  discountSummary.value = discountSummaryData || []
  shopInfo.value = detailData.value.shopInfo || {}

  let number = Math.max(...numberList)
  let newTableData = []

  for (let index = 0; index < number; index++) {
    let table = {}
    if (payTypeSummary[index]) {
      table.payTypeClient = payTypeSummary[index].client
      table.payTypemMoney = payTypeSummary[index].money
      table.payTypemNum = parseInt(payTypeSummary[index].num)
    }
    if (discountSummaryData[index]) {
      table.discountSummaryMoney = discountSummaryData[index].money
      table.discountSummaryName = discountSummaryData[index].name
    }
    if (backList[index]) {
      table.backListName = backList[index].name
      table.backListMoney = backList[index].money
      table.backListNum = parseInt(backList[index].num)
    }
    if (foodList[index]) {
      table.foodListName = foodList[index].name
      table.foodListMoney = foodList[index].money
      table.foodListNum = parseInt(foodList[index].num)
    }
    if (presentList[index]) {
      table.presentListName = presentList[index].name
      table.presentListMoney = presentList[index].money
      table.presentListNum = parseInt(presentList[index].num)
    }
    if (index === 0) {
      table = { ...table, ...summaryData }
    }
    newTableData.push(table)
  }

  tableData.value = newTableData
}

// 切换统计方式
const showCategoryStatistics = () => {
  isCategoryStatistics.value = !isCategoryStatistics.value
  if (isCategoryStatistics.value) {
    categoryStatistics()
  } else {
    foodStatistics()
  }
}

// 按菜品统计
const foodStatistics = () => {
  let payTypeSummary = detailData.value.payTypeSummary?.list || []
  let summaryData = detailData.value.summary || {}
  let discountSummaryData = detailData.value.discountSummary?.list || []
  let backList = detailData.value.backList || []
  let foodList = detailData.value.foodList || []
  let presentList = detailData.value.presentList || []

  let numberList = [
    payTypeSummary.length,
    discountSummaryData.length,
    backList.length,
    foodList.length,
    presentList.length
  ]

  payMethodsList.value = payTypeSummary || []
  returnFoodList.value = backList || []
  summary.value = summaryData || {}
  discountSummary.value = discountSummaryData || []
  shopInfo.value = detailData.value.shopInfo || {}

  let number = Math.max(...numberList)
  let newTableData = []

  for (let index = 0; index < number; index++) {
    let table = {}
    if (payTypeSummary[index]) {
      table.payTypeClient = payTypeSummary[index].client
      table.payTypemMoney = payTypeSummary[index].money
      table.payTypemNum = parseInt(payTypeSummary[index].num)
    }
    if (discountSummaryData[index]) {
      table.discountSummaryMoney = discountSummaryData[index].money
      table.discountSummaryName = discountSummaryData[index].name
    }
    if (backList[index]) {
      table.backListName = backList[index].name
      table.backListMoney = backList[index].money
      table.backListNum = parseInt(backList[index].num)
    }
    if (foodList[index]) {
      table.foodListName = foodList[index].name
      table.foodListMoney = foodList[index].money
      table.foodListNum = parseInt(foodList[index].num)
    }
    if (presentList[index]) {
      table.presentListName = presentList[index].name
      table.presentListMoney = presentList[index].money
      table.presentListNum = parseInt(presentList[index].num)
    }
    if (index === 0) {
      table = { ...table, ...summaryData }
    }
    newTableData.push(table)
  }

  tableData.value = newTableData
}

// 获取列表数据
const fetchSalesReport = () => {
  let start_time = ''
  let end_time = ''
  if (dateRangeList.value) {
    start_time = dateRangeList.value[0] + ' 00:00:00'
    end_time = dateRangeList.value[1] + ' 23:59:59'
  }

  tableLoading.value = true
  cardLoading.value = true

  salesReport({
    start_time: start_time,
    end_time: end_time,
    time_slot: searchParam.value.time_slot,
    print: '0'
  })
    .then(res => {
      detailData.value = res.data.detail
      if (isCategoryStatistics.value) {
        categoryStatistics()
      } else {
        foodStatistics()
      }
    })
    .catch(error => {
      ElMessage.error('获取数据失败，请重试')
    })
    .finally(() => {
      tableLoading.value = false
      cardLoading.value = false
    })
}

// 查询表单
const queryForm = () => {
  fetchSalesReport()
}

// 单选事件处理
const singleElection = () => {
  // 可以根据需要实现
}

const getDeskOrderList = () => {
  // 可以根据需要实现
}

// 组件挂载时执行
onMounted(() => {
  const { currentNowDate } = getNowDateAndTime()
  dateRangeList.value = [currentNowDate + ' ', currentNowDate + ' ']
  fetchSalesReport()
})
</script>

<style lang="scss" scoped src="./modules/dailySaleSummary.scss"></style>
